package jjoms.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jjoms.model.item.CartVO;
import jjoms.model.item.ItemService;
import jjoms.model.item.ItemVO;
import jjoms.model.item.MessageVO;
import jjoms.model.item.PostVO;
import jjoms.model.member.MemberService;
import jjoms.model.member.MemberVO;

import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/item")
public class ItemController {
	@Resource(name = "itemServiceImpl")
	private ItemService itemService;

	@Resource(name = "memberServiceImpl")
	private MemberService memberService;

	@Resource(name = "uploadPath")
	private String path;

	@RequestMapping("/getItemList.moja")
	public ModelAndView getItemList(String keyword) {
		ModelAndView mv = null;
		
		
		System.out.println("getItemList(item)-들어온 키워드값 : " + keyword);
		
		List<ItemVO> list = itemService.getItemList(keyword);
		System.out.println("검색된 list = " + list);
		if(list.size()>0){
			mv = new ModelAndView("getItemList.item", "list", list);
		}else{
			mv = new ModelAndView("getItemListFail.item", "keyword", keyword);
		}
	//	return new ModelAndView("getItemList.item", "list", list);
		return mv;
	}

	@RequestMapping("/showItemContent.moja")
	public ModelAndView showItemContent(int itemNo) {
		System.out.println("showItemContent(item)-들어온 글번호 : " + itemNo);
		Map<String, ArrayList<String>> map = null;
		ArrayList<String> kList = new ArrayList<String>();
		ArrayList<String> list = new ArrayList<String>();
		ItemVO ivo = itemService.getItemContent(itemNo);
		System.out.println("검색된 ivo = " + ivo);
		System.out.println("category" + ivo.getCategory());

		// System.out.println("map=" + map);
		// ModelAndView mv = new ModelAndView("showItemContent.item");
		// mv.addObject("ivo", ivo);
		// mv.addObject("map", map);
		return new ModelAndView("showItemContent.item", "ivo", ivo);
		// return mv;
	}

	@RequestMapping("/item_register.moja")
	public String registerView() {
		System.out.println("registerView view!!");
		return "item_register.item";
	}

	@RequestMapping("/auth_register.moja")
	public ModelAndView register(HttpServletRequest request, ItemVO vo) {
		System.out.println("의현아ㅠㅠ:" + vo);

		HashMap<String, ArrayList> map = (HashMap<String, ArrayList>) request.getParameterMap();

		String category = ""; // 카테고리 목록이 (카테고리1,카테고리2) 형태의 String 타입으로 저장

		System.out.println("map 엔 뭐가 ???? " + map);
		Set<String> set = map.keySet();
		System.out.println("set 엔 뭐가 ???? " + set);
		Iterator<String> it = set.iterator();
		System.out.println("it엔 무엇이???????" + it);
		while (it.hasNext()) {
			String name = it.next();
			String value[] = request.getParameterValues(name);

			for (int i = 0; i < value.length; i++) {
				if (!name.equals("itemName") && !name.equals("itemPrice")
						&& !name.equals("memberId")
						&& !name.equals("uploadFile")
						&& !name.equals("fileDir") && !name.equals("itemInfo")) {
					System.out.println("for문 돌린 후.....name == " + name);
					System.out.println("for문 돌린 후.....value == " + value[i]);
					System.out.println("i값 = " + i + " length = "
							+ value.length);
					if (i > 1 && i == value.length - 1)
						category = category + name + "-" + value[i];
					else
						category = category + name + "-" + value[i] + ",";
					System.out.println("1");
				}// if
				System.out.println("2");
			}// for
			System.out.println("category == " + category);
			vo.setCategory(category);

		}// while

		System.out.println("vo : " + vo);
		itemService.register(vo); // 상품 등록
		// 상품 등록후 카테고리 등록
		System.out.println("insert후" + vo);
		return new ModelAndView("redirect:showItemContent.moja?itemNo="
				+ vo.getItemNo());
	}

	@RequestMapping("/registerResult.moja")
	public ModelAndView registerResult(String name)
			throws UnsupportedEncodingException {
		System.out.println("registerResult : " + name);
		name = URLDecoder.decode(name, "utf-8");
		ItemVO vo = itemService.findItemByName(name);
		return new ModelAndView("item/showItemContent.item", "vo", vo);
	}

	@RequestMapping("/auth_updateItemContentPost.moja")
	public ModelAndView updateItemContentPost(int itemNo) {
		System.out.println("updateItemContentPost(item)-들어온 글번호 : " + itemNo);
		ItemVO ivo = itemService.getItemContent(itemNo);
		HashMap<String, ArrayList> map = itemService.getCategory();
		System.out.println("controller 검색후 map : " + map);
		System.out.println("검색된 ivo = " + ivo);
		ModelAndView mv = new ModelAndView("item_update.item");
		mv.addObject("ivo", ivo);
		mv.addObject("map", map);
		return mv;
	}

	@RequestMapping("/update.moja")
	public ModelAndView update(ItemVO vo) {
		System.out.println("vo : " + vo);
		itemService.update(vo);
		System.out.println("update후" + vo);
		return new ModelAndView("redirect:showItemContent.moja?itemNo="
				+ vo.getItemNo());
	}

	@RequestMapping("/delete.moja")
	public ModelAndView delete(int itemNo, HttpServletRequest request) {
		System.out.println("delete vo : " + itemNo);
		itemService.delete(itemNo);

		return new ModelAndView("redirect:/member/home.moja");
	}

/*	@RequestMapping("/insertPurchasedItemList.moja")
	public ModelAndView purchasedItemList(int itemNo,int itemPrice, String memberId,int memberPoint,String selId, String fileDir, String sellerId,
			HttpServletRequest request, HttpSession session) {
		// 구매목록 리스트에 삽입
		System.out.println("영일::::::" + itemNo);
		ItemVO vo = itemService.getItemContent(itemNo);
		session = request.getSession(false);
		MemberVO mvo2 = (MemberVO) session.getAttribute("mvo");

		System.out.println("vooooo:" + vo);
		vo.setMemberId(mvo2.getMemberId());

		itemService.insertToPurchasedList(vo);
		//System.out.println("ㅅㅁㅁㅁㅁㅁㅁㅁㅁㅁ" + vo.getFileDir());
		return new ModelAndView("redirect:showPurchasedItemList.moja?fileDir="
				+ vo.getFileDir());
		return new ModelAndView("redirect:showItemContent.moja?itemNo="+itemNo);
		//return new ModelAndView("redirect:fileDownloadPoint.moja?itemPrice="+itemPrice+"&memberId="+memberId+"&memberPoint="+memberPoint+"&selId="+selId+"&fileDir="+fileDir+"&sellerId="+sellerId);
	}*/ // 필요 없음

	@RequestMapping("/showPurchasedItemList.moja")
	public ModelAndView showPurchasedItemList(HttpServletRequest request, HttpSession session) {
		// 구매목록리스트 호출~
		session = request.getSession(false);
		MemberVO vo = (MemberVO) session.getAttribute("mvo");
		ArrayList<ItemVO> ivoList = (ArrayList<ItemVO>) itemService.getPurchasedList(vo.getMemberId());
		
		System.out.println("구매목록리스트:::!!!"+ivoList);
		//System.out.println("ㅠㅠㅠㅠ:" + ivo.getFileDir());
		return new ModelAndView("getPurchasedItemList.item", "ivoList", ivoList);
	}

	@RequestMapping("/fileDownload.moja")
	public ModelAndView fileDownload(String filename,HttpServletRequest request,int itemNo) {
		//System.out.println("filedownload " + filename);
		System.out.println("********************************");
		System.out.println("itemNo"+ itemNo);
		ItemVO ivo = itemService.getItemContent(itemNo);
		System.out.println("검색된 ivo"+ ivo);
		filename = ivo.getMemberId() + "\\" + ivo.getFileDir();
		HashMap map = new HashMap();
		map.put("path", path);
		map.put("filename", filename);
		return new ModelAndView("downloadView", map);
	}

	// 지수야 잠깐만 닫아놓을게
	/*
	 * 파일 다운로드(구매) 순서
	 * 
	 * 1 ) 구매 금액이나 포인트의 가격이 상품 금액보다 같거나 큰지 확인 작으면 return;- ShowItemcontent.jsp에서 ajax로 가는게 좋을듯
	 * 
	 * 2)  가격이 맞으면 fileDownloadPoint 로 데이터를 보내서 구매자의 금액을 차감하고 판매자에게 판매금의 80%를 입금 한다.
	 * 
	 * 3) 구매 상품을 사용자의 구매목록에 추가 시켜준다.
	 * 
	 * 4) DownloadController로 보내 다운로드를 실행한다.
	 * 
	 * 5) 페이지를 구매완료 페이지로 이동시킨다.  
	 * 
	 */
	@Transactional
	@RequestMapping("/fileDownloadPoint.moja")
	public ModelAndView fileDownloadPoint(String memberId, int itemNo,String sellerId, String fileDir, HttpServletRequest request, HttpSession session) {
		System.out.println("----------------------------------------------------");
		System.out.println("fleDownloadPoint");
		System.out.println("----------------------------------------------------");
		MemberVO mvo = (MemberVO) session.getAttribute("mvo");
		System.out.println("구매자 id : " + mvo.getMemberId() );
		System.out.println("상품 번호 : " + itemNo);
		
		ModelAndView mv = null;
		//구매자가 파일을 구매 했는지 안했는지 확인 하는 메서드
		
		
		//아이템과 구매자의 데이터를 검색해와 각자 VO객체에 저장 시킨다. 		
		//구매자의 금액을 차감하고 - 판매자에게 판매금액의 80%의 금액을 입금
		// 입금 완료되면 포인트 증가 
		// 이 모든걸 하나의 메서드로 
		
		try {
			//구매자의 금액 차막, 포인트 증가 , 판매자의 금액 증가
			itemService.updateMoneyAndPoint(mvo.getMemberId(), itemNo); 
			//구매자의 구매등록 리스트에 데이터 입력
			itemService.insertToPurchasedList(mvo.getMemberId(), itemNo);
			MemberVO mvo2 = memberService.findMemberById(mvo.getMemberId());
			session.setAttribute("mvo", mvo2);
			
		} catch (Exception e) {
			System.out.println("입출금 에러");
		}finally{
			mv = new ModelAndView("redirect:showPurchasedItemList.moja");
		}
		
		//	System.out.println("파일경로"+fileDir);
		//mv = new ModelAndView("redirect:fileDownload.moja?filename="+sellerId+"\\"+fileDir);
		
		return mv;
	}

	@RequestMapping("/auth_getCategory.moja")
	public ModelAndView getCategory(String memberId, HttpSession session,
			HttpServletRequest request, ItemVO ivo) {
		ModelAndView mv = null;
		session = request.getSession(false);
		MemberVO mvo = (MemberVO) session.getAttribute("mvo");
		if(mvo == null){
			System.out.println("로긴 안함");
			mv = new ModelAndView("item_fail.item");
		}else if (!mvo.getMemberSellAuthority().equals("pass")) {
			System.out.println("판매권한이 없음");
			mv = new ModelAndView("item_fail.item");

		} else {
			System.out.println("getCategory");
			System.out.println("getCategory memberId ==" + memberId);
			HashMap<String, ArrayList> map = itemService.getCategory();
			System.out.println("controller 검색후 map : " + map);
			session.setAttribute("memberId", memberId);
			mv = new ModelAndView("item_register.item", "map", map);
			mv.addObject("ivo", ivo);
		}
		return mv;
	}

	@RequestMapping("/addCart.moja")
	public String addCart(ItemVO ivo, CartVO cvo, MemberVO mvo) {
		System.out.println("addCart Controller 접속확인 == " + mvo.getMemberId()
				+ " / " + ivo.getItemNo());
		cvo.setMemberId(mvo.getMemberId());
		cvo.setItemNo(ivo.getItemNo());
		System.out.println("cvo에 set한 후 확인 == " + cvo);
		itemService.addCart(cvo);
		System.out.println("insert후 cvo == " + cvo.toString());
		return "home";
		// return "getCartList.moja?memberId="+mvo.getMemberId();
	}

	@RequestMapping("/getCartList.moja")
	public ModelAndView getCartList(String memberId, ItemVO ivo) {
		System.out.println("getCartList memberId == " + memberId); // 로그인된 아이디
		// System.out.println("getCartList itemNo == "+ivo.getItemNo());
		List<CartVO> vo = itemService.getCartList(memberId); // 로그인 한 아이디가 갖고있는
																// 카트
		System.out.println("select 후 == " + vo);

		List<ItemVO> cList = new ArrayList();
		System.out.println("요기?????");
		for (int i = 0; i < vo.size(); i++) {
			System.out.println("저기?????");
			System.out.println("null일까????"
					+ itemService.getCartInfoList(vo.get(i).getItemNo()));
			cList.add(itemService.getCartInfoList(vo.get(i).getItemNo()));
		}
		System.out.println("222==" + cList);
		// System.out.println("로그인 한 아이디가 갖고있던 상품의 정보 == "+cvo);
		return new ModelAndView("getCartList.item", "cvo", cList);
	}

	@RequestMapping("/postResult.moja")
	@ResponseBody
	public HashMap postResult(ItemVO ivo, PostVO pvo, MemberVO mvo,
			String memberId, int itemNo, int starEvaluation) {
		float count = 0;
		System.out.println("스타평점 컨트롤러:" + starEvaluation);
		System.out.println("itemName:" + ivo.getItemName());
		pvo.setItemNo(ivo.getItemNo());
		pvo.setItemName(ivo.getItemName());
		pvo.setMemberId(mvo.getMemberId());
		pvo.setStarEvaluation(starEvaluation);
		System.out.println("pvo에 setting한 후 확인 == " + pvo.toString());
		itemService.postResult(pvo);
		System.out.println("pvo에 insert한 후 확인 == " + pvo.toString());
		// List<PostVO> list = itemService.getPostHuki();
		List<PostVO> list = itemService.getPostHuki(pvo.getItemNo());
		count = itemService.getAverageEvaluation(itemNo);
		HashMap map = new HashMap();
		map.put("list", list);
		map.put("count", count);
		return map;
	}

	@RequestMapping("/postGet.moja")
	@ResponseBody
	public HashMap postGet(ItemVO ivo, PostVO pvo, MemberVO mvo,
			String memberId, int itemNo) {
		int count = 0;
		System.out.println("후기보기");
		System.out.println(ivo);
		System.out.println(pvo);
		System.out.println(mvo);
		System.out.println(itemNo);
		List<PostVO> list = itemService.getPostHuki(ivo.getItemNo());
		System.out.println(list);
		if(list.size()>0){
		count = itemService.getAverageEvaluation(itemNo);
		}
		System.out.println(count);
		HashMap map = new HashMap();
		map.put("list", list);
		map.put("count", count);
		return map;
	}

	@RequestMapping("/getAverageEvaluation.moja")
	@ResponseBody
	public int getAverageEvaluation(int itemNo) {
		// System.out.println("바봄ㅇㄴㄹ:"+itemNo);
		int count = 0;
		count = itemService.getAverageEvaluation(itemNo);
		return count;
	}

	@RequestMapping("/messageInsertView.moja")
	public ModelAndView messageInsertView(ItemVO ivo) {

		return new ModelAndView("messageInsertView.item", "ivo", ivo);
	}

	@RequestMapping("/sendMessage.moja")
	public String sendMessage(HttpServletRequest request, MessageVO messvo,
			HttpSession session, int itemNo) {
		session = request.getSession(false);
		MemberVO mvo = (MemberVO) session.getAttribute("mvo");
		messvo.setSender(mvo.getMemberId());
		System.out.println("으라차차 메세지vo입력:" + messvo);
		itemService.sendMessage(messvo);
		//String memberId = messvo.getMemberId();
		return "redirect:showItemContent.moja?itemNo=" + itemNo;
	}

	public ModelAndView addCartCount() {

		return null;

	}

	@RequestMapping("/postDelete.moja")
	public ModelAndView postDelete(PostVO pvo) {
		itemService.postDelete(pvo);
		return new ModelAndView("redirect:showItemContent.moja?itemNo="
				+ pvo.getItemNo());
	}
	@RequestMapping("/showUploadList.moja")
	public ModelAndView showUploadList(String memberId){
		ModelAndView mv = null;
		ArrayList<ItemVO> list=(ArrayList<ItemVO>) itemService.showUploadList(memberId);
		mv=new ModelAndView("showAllUploadList.item","list",list);
		return mv;
	}
	
	@RequestMapping("/cartCheck.moja")
	@ResponseBody
	public int cartCheck(int price, int totalPrice) {
		System.out.println("price=="+price);
		totalPrice += price;
		 System.out.println("total=="+totalPrice);
		return totalPrice;
	}
	
	@RequestMapping("/cartDelete.moja")
	@ResponseBody
	public ModelAndView cartDelete(int no) {
		itemService.cartDelete(no); //db에서 cart삭제
		
		return new ModelAndView("getCartList.moja");
	}
	
	
}